import Koa from 'koa';
import KoaBody from 'koa-body';
import cors from 'koa2-cors';
import KoaJwt from 'koa-jwt';
import routers from './router';
import log from './utils/log';
import MuseumUserMange from './core/MuseumUserMange';
import './task';

const app = new Koa();
global.userManager = new MuseumUserMange();


app.use(KoaBody({ multipart: true, formLimit: '20mb' }));
app.use(cors());

app.use((ctx, next) => {
  return next().catch((err) => {
    if(err.status === 401){
      ctx.status = 401;
      ctx.body = 'Protected resource, use Authorization header to get access\n';
    }else{
      throw err;
    }
  })
})

app.use(KoaJwt({
  secret: 'login_token'
}).unless({ // 配置白名单
  path: [/\/api\/login/]
}))

//加载路由
app.use(routers.routes()).use(routers.allowedMethods());

const port = process.env.PORT || '8082';
app.listen(port, function () {
    log.info('服务器启动');
    console.log(`服务器运行在http://127.0.0.1:${port}`);
    // RefreshNginx();
});
